<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Wxserve;
use app\common\service\TenIM;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        
        $this->view->assign("orderTypeList", $this->model->orderTypeList());
        $this->view->assign("payTypeList", $this->model->payTypeList());
        $this->view->assign("statusList1", $this->model->statusList());
        
        $this->view->assign("isevalList1", $this->model->isevalList());
        $this->view->assign("refStatusFbList1", $this->model->refStatusFbList());
        $this->view->assign("resStatusList", $this->model->resStatusList());
        $this->view->assign("isAbnormalList", $this->model->isAbnormalList());
        //is_abnormal
        

    }
    
    // public function res_qx($ids){
    //       //取消订单 
    //       // 返回定稿的剩余时间？
    //       $order = db("order")->Where("id",$ids)->field("dg_sy_time,is_gai_time_add")->find();
    //       //
          
   
          
    //       $z = [];
    //       $z["is_gai_time_add"] = time() - $order["dg_sy_time"];
    //       $z["res_status"] = 0;
    //       $z["is_acceptance"] = 0;
          
    //       db("appeal_new")->where(["aid"=>$ids])->setField(['status'=>'拒绝处理',"update_time"=>date("Y-m-d H:i:s")]);
    //     //   dump($z);die;
    //       db("order")->Where("id",$ids)->setField($z);
    //       return json(["code"=>1,"msg"=>"操作问题"]);
    // }

    
       public function index($ctype=0)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        // if ($this->request->request('keyField')) {
        //     return $this->selectpage();
        // }
         
        $wheres = "";
        if(!empty($ctype)){
            
            $ctype =  substr($ctype,0,1);
       
            switch ($ctype) {
                case '1':
                    $wheres = "is_abnormal>0 and m.status<5";
                    // code...
                    break;
                case '2':
                    $wheres = "ref_status_fb>0 and m.status<5";
                    // code...
                    break;
                case '3':
                    $wheres = "res_status>0 and m.status<5";
                    // code...
                    break;
                case '4':
                    $wheres = " m.status=5";
                    // code...
                    break;    
                default:
                     $wheres = "m.status<5";
                    break;
            }
           
        }

        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->alias("m")
            ->field("m.*,m.status as 'm.status',u.mobile as 'u.mobile',w.mobile as 'w.mobile',u.dream_id as 'u.dream_id',w.dream_id as 'w.dream_id'")
            ->join("membe u","u.membe_id=m.uid","left")    
            ->join("membe w","w.membe_id=m.writer_uid","left")    
            ->where($where)
            ->where($wheres)
            ->where("m.status>0")
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


   
    public function edit($ids = null)
    {
        
        $mtype = input("mtype/d",0);
    
         if($mtype == 6){
             //处理申诉
            $params = $this->request->post('row/a');
             
              
            $order = db("order")->Where("id",$ids)->field("id,dg_sy_time,is_gai_time_add,out_trade_no")->find();
          //
          
          //是否有退款未处理的？
           $order_ref = db("order_ref")->where(["refs_status"=>0,"oid"=>$ids])->field("apply_time_s,tk_sy_time,id")->select();
            foreach ($order_ref as $k=>$v){
                 $end_times =  time() - $v["tk_sy_time"];
                 db("order_ref")->where(["id"=>$v["id"]])->setField(["apply_time_s"=>$end_times]);
            } 
  

          $z = [];
          $z["is_gai_time_add"] = time() - $order["dg_sy_time"];
          $z["res_status"] = 0;
          $z["is_acceptance"] = 0;
         $appeal_new =db("appeal_new")->where(["aid"=>$ids,"status"=>"待处理"])->select();
        //  dump($appeal_new);die;
         foreach ($appeal_new as $k=>$v){
            
            $new_arr_json = [];
            $new_arr_json["type"] = 6;
            $new_arr_json["aid"] = $v['aid'];
            // $new_arr_json["username"] = $user['username'];
            $new_arr_json["title"] = '您申诉状态的订单平台已处理';//urldecode($info['title']);
            $new_arr_json["left_1"] = "订单编号：";
            $new_arr_json["left_1_val"] = $order["out_trade_no"];
            $new_arr_json["left_2"] = "处理结果：";
            $new_arr_json["left_2_val"] = "拒绝申诉";
            $new_arr_json["left_3"] = "温馨提示：";
            $new_arr_json["left_3_val"] = $params["u_tip"];
            (new TenIM)->sendSystemMsg($v['uid'],'type'.json_encode($new_arr_json));
        }
            
        db("appeal_new")->where(["aid"=>$ids])->setField(['status'=>'拒绝处理',"err_cnt"=>$params["err_cnt"],"update_time"=>date("Y-m-d H:i:s")]);
        //   dump($z);die;

        
          db("order")->Where("id",$ids)->setField($z);
          return json(["code"=>1,"msg"=>"操作问题"]);;
         }
         
         if($mtype == 4 ){
            
           $order = $model =  db("order")->where('id', $ids)->find();
            if ($model) {
  
                // 如果有退款中的订单  不能点确认完成
                $ref_order = db("order_ref")->where(["oid"=>$ids,'refs_status'=>0])->count();
                if($ref_order>0){
                     $this->error("该订单有申请退款且未处理的情况，请先进行处理");
                }
                
                //哪判断如果确认过订单了  不允许再确认了
                if($model["status"] != "2" && $model["status"] != "3"){
                     $this->error("只有已接单未完成的订单才能确认完成");
                }
                
                 $params = $this->request->post('row/a');
                 
                 $tuikuan = $model["price"] - $model["ref_money"];
                //不能超过  可退金额
                if($params["t_price"] >= $tuikuan){
                     $this->error("最多可退款".($model["price"] - $model["ref_money"]-1));
                }
             
                // if($tuikuan - $params["t_price"] < 1){
                //      $this->error("写手最少要保留1块钱");
                // }
                if($params["t_price"]<0){
                     $this->error("不能小于0");
                }
             
                $price = $params["t_price"];
             //$order_ref
             $z = [];
            $z["oid"] = $ids;
            $z["out_trade_no"] = $model["out_trade_no"];
            $z["uid"] = $order["uid"];
            $z["writer_uid"] = $model["writer_uid"];
            $z["num"] = 1;
            
            
            $z["refs_money_cont"] = "系统判定退款";//退款原因
            $z["refs_money_desc"] = "系统判定退款";//退款原因
            $z["refs_money_imgs"] = "";
           
          
            $z["apply_time"] = date("Y-m-d H:i:s");
            $z["ref_status"] = 1;
            $z["price"] = $price;
            $ref_id = db("order_ref")->insertGetId($z);
                
           
           //需要新增1个部分退款的流程
              $res = db("order")->Where(["id"=>$ids])->update(['ref_status' => 1,"res_status"=>2,"is_tk"=>1,"is_acceptance"=>0,"ref_status_fb"=>1, 'update_time' => time(),"ss_status"=>$order["status"]]);
              
               db("appeal_new")->where(['aid'=>$ids,"status"=>'待处理',"type"=>6])->update(["status"=>"已处理"]);
              
              db("order")->Where(["id"=>$ids])->inc('ref_num',1)->update();
              db("order")->Where(["id"=>$ids])->inc('ref_money',$params["t_price"])->update();   
              db("order_ref")->where(["id"=>$ref_id])->update(["refs_status"=>1,"end_time"=>date("Y-m-d H:i:s")]);
     
     
        //   $user = db("membe")->where("membe_id",$order['uid'])->field("pic,username")->find();
        //   $wuser = db("membe")->where("membe_id",$order['writer_uid'])->field("pic,username")->find();
           
                    // 退回用户支付费用
               $save = db("membe")->where('membe_id', $model['uid'])->inc('wallet',$params["t_price"])->update();
               
                    
                // 记录写手入账日志
                $arr['uid'] = $model['uid'];
                $arr['type'] = 8;
                $arr['oid'] = $ids;
                $arr['jie_type'] = 1;
                $arr['price'] = $price;
                $arr['create_time'] = time();
                db("finance_log")->insert($arr);
                
                
            //  (new OrderLog)->addLog($model['id'], 1,$model["uid"], '部分退款订单，订单金额：' . $params['t_price'] . '元自动转入粮币，订单号：' . $model['out_trade_no']);
                
                $base_config = db("base_config")->where(["name"=>"service_charge"])->Value("data");
              
              
                $order = $model = db("order")->where('id', $ids)->find();
              //再确认订单？
              
                // 更新写手佣金
                $user = db("membe")->where('membe_id', $model['writer_uid'])->find();
              
                // 更新订单状态
                // db("order")->where(["id"=>$ids])->setField(['res_status' => 1,'is_acceptance'=>1,"ss_status"=>$order["status"], 'update_time' => time(),"qr_time"=>date("Y-m-d H:i:s")]);
                
                
                // 计算平台服务费扣除后到账金额
                $price = ($model['price']-$model["ref_money"]) * (1 - ($base_config / 100));
                // 更新写手可提现金额/佣金额度
                db("membe")->where(["membe_id"=>$model["writer_uid"]])->setInc('commission', $price);
  
                
                // 记录写手入账日志
                $arr['uid'] = $model['writer_uid'];
                $arr['type'] = 5;
                $arr['oid'] = $ids;
                $arr['jie_type'] = 1;
                $arr['price'] = $price;
                $arr['create_time'] = time();
                db("finance_log")->insert($arr);
                
                db("membe")->where(["membe_id"=>$model["uid"]])->setInc('user_exp',  $model['price']);
                
                // 更新用户经验值
                // (new UserModel)->where('membe_id', TokenService::getCurrentUid())->inc('user_exp', $model['price'])->update();
                
                $userexp = db("membe")->where("membe_id",$model["uid"])->value("user_exp");
                $new_user_level = db("vip_rank")->where("exp<".$userexp)->order("id desc")->value("id");
            
                //用户级别
                if(!empty($new_user_level)){
                     db("membe")->where("membe_id",$model["uid"])->update(["u_level"=>$new_user_level]);
                     
                }
                $writer_exp = $user["writer_exp"] + $model['price'];
                      
                // 更新写手经验值
                db("membe")->where(["membe_id"=>$model["writer_uid"]])->setInc('writer_exp',  $model['price']);
                
            
                //计算写手当前级别
                $new_level = db("writer_rank")->where("exp<".$writer_exp)->order("id desc")->value("title");
                 
                if(!empty($new_level)){
                      
                     db("membe")->where("membe_id",$model['writer_uid'])->update(["w_level"=>$new_level]);
                        // $user->update(["w_level"=>$new_level]);    
                }
            
                
                //更新用户这个橱窗类型的 购买数量和评分 ->inc('commission', $price)->update();
                db("writer_goods")->where(["id"=>$model["gid"]])->setInc("buy_num",1);
                
                
                
                // (new OrderLog)->addLog($data['id'], 1, TokenService::getCurrentUid(), '用户确认完成订单，订单号：' . $model['out_trade_no']);
                // (new UserLog)->handle('用户确认完成订单，订单号：' . $model['out_trade_no']);
                // (new TenIM)->sendSystemMsg($model['writer']['membe_id'], '用户《' . $model['user']['username'] . '》确认完成订单，订单号：' . $model['out_trade_no']);
                
                  $wx_openid = db("membe")->where(["membe_id"=>$model['writer_uid']])->value("wx_openid");
                 if(!empty($wx_openid)){
                     $Wxserve = new Wxserve;
                     $wx_data["orderNo"] = $model["out_trade_no"];
                     $wx_data["c_title"] = "橱窗名称:".mb_substr($model["c_title"],0,14);
                     $wx_data["orderNo"] = $model["out_trade_no"];
                     $wx_data["price"] = $model["price"];
                     $resault = $Wxserve->wc_order_msg($wx_openid,$wx_data);
                 }
                
                $new_arr_json = [];
                $new_arr_json["type"] = 6;
                $new_arr_json["aid"] = $model['id'];
                // $new_arr_json["username"] = $user['username'];
                $new_arr_json["title"] = '您申诉状态的订单平台已处理';//urldecode($info['title']);
                $new_arr_json["left_1"] = "订单编号：";
                $new_arr_json["left_1_val"] = $order["out_trade_no"];
                $new_arr_json["left_2"] = "处理结果：";
                $new_arr_json["left_2_val"] = "已完成订单（含部分退款）";
                $new_arr_json["left_3"] = "温馨提示：";
                $new_arr_json["left_3_val"] = $params["u_tip"];
                (new TenIM)->sendSystemMsg($model['writer_uid'],'type'.json_encode($new_arr_json));
                
                
                
                
                $new_arr_json = [];
                $new_arr_json["type"] = 6;
                $new_arr_json["aid"] = $model['id'];
                // $new_arr_json["username"] = $user['username'];
                $new_arr_json["title"] = '您申诉状态的订单平台已处理';//urldecode($info['title']);
                $new_arr_json["left_1"] = "订单编号：";
                $new_arr_json["left_1_val"] = $order["out_trade_no"];
                $new_arr_json["left_2"] = "处理结果：";
                $new_arr_json["left_2_val"] = "已完成订单（含部分退款）";
                $new_arr_json["left_3"] = "温馨提示：";
                $new_arr_json["left_3_val"] = $params["w_tip"];
                (new TenIM)->sendSystemMsg($model['writer_uid'],'type'.json_encode($new_arr_json));
                
                
                
                
                
                
                $this->success("操作成功");
            } else {
                $this->error('订单更新失败');
            }
            //处理完成订单
            $this->success("操作成功");
        }
        
        
        if($mtype == 3){
            $data = input("post.");
     
            $model = db("order")->Where(["id"=>$ids])->find();
          
             $price = $model["price"] - $model["ref_money"];
          
                  if($model["status"] < 2 || $model["status"] >4 ){
                      $this->error("只有进行中的订单才可取消");
                 }
                 
                    $arr['uid'] = $model['uid'];
                    $arr['type'] = 7;
                    $arr['use_type'] = 2;
                    $arr['jie_type'] = 1;
                    $arr['price'] = $price;
                    $arr['create_time'] = time();
                    db("finance_log")->insert($arr);
                    $res = db("order")->where(["id"=>$ids])->setField(["is_zd"=>1,'is_acceptance'=>1,"ss_status"=>$model["status"],"t_price"=>$price,'status' => 5,"ref_status"=>1,"ref_status_fb"=>2, 'update_time' => time()]);
                    
                    db("membe")->where('membe_id', $model['uid'])->inc('wallet', $price)->update();
                    db("order_log")->insert(["oid"=>$model["id"],"user_type"=>'1',"uid"=>$model["uid"],"msg"=> '取消订单，订单金额：' . $price. '元自动转入粮币，订单号：' . $model['out_trade_no']]);
             
                      $wx_openid = db("membe")->where("membe_id",$model['uid'],)->value("wx_openid");
                     if(!empty($wx_openid)){
                         
                         $Wxserve = new Wxserve;
                         $wx_data["orderNo"] = $model["out_trade_no"];
                         $wx_data["price"] = $model["price"];
                         $wx_data["cv_price"] = $model["cv_price"];
                         $wx_data["pay_time"] = $model["pay_time"];
                         $resault = $Wxserve->qx_order_msg($wx_openid,$wx_data);
                     }
               
                      $wx_openid = db("membe")->where("membe_id",$model['writer_uid'],)->value("wx_openid");
                     if(!empty($wx_openid)){
                         
                         $Wxserve = new Wxserve;
                         $wx_data["orderNo"] = $model["out_trade_no"];
                         $wx_data["price"] = $model["price"];
                         $wx_data["cv_price"] = $model["cv_price"];
                         $wx_data["pay_time"] = $model["pay_time"];
                         $resault = $Wxserve->qx_order_msg($wx_openid,$wx_data);
                     }
               
                    
            $this->success("操作成功");
        }
        
        if($mtype == 2 ){
            
            
        
            $model =  db("order")->where('id', $ids)->find();
            if ($model) {
  
                //如果有退款中的订单  不能点确认完成
                $ref_order = db("order_ref")->where(["oid"=>$ids,'refs_status'=>0])->count();
                if($ref_order>0){
                     $this->error("该订单有申请退款且未处理的情况，请先进行处理");
                }
                
                //哪判断如果确认过订单了  不允许再确认了
                if($model["status"] != "2" && $model["status"] != "3"){
                     $this->error("只有已接单未完成的订单才能确认完成");
                }
                
                $base_config = db("base_config")->where(["name"=>"service_charge"])->Value("data");
              
                // 更新写手佣金
                $user = db("membe")->where('membe_id', $model['writer_uid'])->find();
              
                
                  
                // 更新订单状态
                db("order")->where(["id"=>$ids])->setField(['status' => 4,'is_acceptance'=>1,"ss_status"=>$model["status"],"is_res"=>1, 'update_time' => time(),"qr_time"=>date("Y-m-d H:i:s")]);
                
                
                // 计算平台服务费扣除后到账金额
                $price = ($model['price'] - $model["ref_money"]) * (1 - ($base_config / 100));
                
                // 更新写手可提现金额/佣金额度
                db("membe")->where(["membe_id"=>$model["writer_uid"]])->setInc('commission', $price);
  
                // 记录写手入账日志
                $arr['uid'] = $model['writer_uid'];
                $arr['type'] = 5;
                $arr['oid'] = $ids;
                $arr['jie_type'] = 1;
                $arr['price'] = $price;
                $arr['create_time'] = time();
                db("finance_log")->insert($arr);
                
                db("membe")->where(["membe_id"=>$model["uid"]])->setInc('user_exp',  $model['price']);
                
                // 更新用户经验值
                // (new UserModel)->where('membe_id', TokenService::getCurrentUid())->inc('user_exp', $model['price'])->update();
                
                $userexp = db("membe")->where("membe_id",$model["uid"])->value("user_exp");
                $new_user_level = db("vip_rank")->where("exp<".$userexp)->order("id desc")->value("id");
            
                //用户级别
                if(!empty($new_user_level)){
                     db("membe")->where("membe_id",$model["uid"])->update(["u_level"=>$new_user_level]);
                     
                }
                $writer_exp = $user["writer_exp"] + $model['price'];
                      
                // 更新写手经验值
                db("membe")->where(["membe_id"=>$model["writer_uid"]])->setInc('writer_exp',  $model['price']);
                
            
                //计算写手当前级别
                $new_level = db("writer_rank")->where("exp<".$writer_exp)->order("id desc")->value("title");
                 
                if(!empty($new_level)){
                      
                     db("membe")->where("membe_id",$model['writer_uid'])->update(["w_level"=>$new_level]);
                        // $user->update(["w_level"=>$new_level]);    
                }
            
                
                //更新用户这个橱窗类型的 购买数量和评分 ->inc('commission', $price)->update();
                db("writer_goods")->where(["id"=>$model["gid"]])->setInc("buy_num",1);
                
                
                
                // (new OrderLog)->addLog($data['id'], 1, TokenService::getCurrentUid(), '用户确认完成订单，订单号：' . $model['out_trade_no']);
                // (new UserLog)->handle('用户确认完成订单，订单号：' . $model['out_trade_no']);
                // (new TenIM)->sendSystemMsg($model['writer']['membe_id'], '用户《' . $model['user']['username'] . '》确认完成订单，订单号：' . $model['out_trade_no']);
                
                  $wx_openid = db("membe")->where(["membe_id"=>$model['writer_uid']])->value("wx_openid");
                 if(!empty($wx_openid)){
                     $Wxserve = new Wxserve;
                     $wx_data["orderNo"] = $model["out_trade_no"];
                     $wx_data["c_title"] = "橱窗名称:".mb_substr($model["c_title"],0,14);
                     $wx_data["orderNo"] = $model["out_trade_no"];
                     $wx_data["price"] = $model["price"];
                     $resault = $Wxserve->wc_order_msg($wx_openid,$wx_data);
                 }
                
                
                $this->success("操作成功");
            } else {
                $this->error('订单更新失败');
            }
            //处理完成订单
            $this->success("操作成功");
        }
        
        $this->view->assign("mtype", $mtype);
         
         
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            
    
            
            if($params["status"] ==2){
                $this->error("暂不支持拒绝");
            }
            
        
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            //订单状态更改？
            if($params["status"] !=0){
                
                if($params["status"] == 1){
                    db("finance_log")->where(["f_id"=>$ids])->update(["f_time"=>date("Y-m-d H:i:s"),"f_status"=>2]);
                }
                if($params["status"] == 4){
                    //通过了的胡
                    
                    db("finance_log")->where(["f_id"=>$ids])->update(["f_time"=>date("Y-m-d H:i:s"),"f_status"=>0,"f_id"=>0]);
                }
            }
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
